package cn.com.headfree.point.controller;

import cn.com.headfree.base.controller.ExBaseController;
import cn.com.headfree.base.controller.ResultData;
import cn.com.headfree.entity.*;
import cn.com.headfree.entity.isc.User;
import cn.com.headfree.point.service.*;
import cn.com.headfree.salary.service.SalaryService;
import cn.com.headfree.util.ExcelExportUtil;
import cn.com.headfree.util.SysDictionaryUtil;
import cn.com.headfree.vo.SysDictionaryInfoVo;
import cn.com.headfree.vo.TPersonYearPointDetailVo;
import com.gta.edu.sdk.common.dto.Page;
import com.gta.edu.sdk.util.StringUtil;
import org.apache.commons.lang.StringUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 *积分管理
 */
@Controller
@RequestMapping(value = "/pointManage", produces = "application/json;charset=UTF-8")
public class PointManageController extends ExBaseController {
	private static final Logger LOG = LogManager.getLogger(PointManageController.class);

	//导出报表表头
	@Value("${personYearPointDetailHead}")
	private String personYearPointDetailHead;

	@Autowired
	private PersonYearPointDetailService personYearPointDetailService;
	@Autowired
	private PersonYearPointService personYearPointService;
	@Autowired
	private SalaryService salaryService;


	/**
	 * 积分管理分页查询
	 */
	@RequestMapping("/findPersonYearPointDetailPageList")
	@ResponseBody
	public ResultData findPersonYearPointDetailPageList(HttpServletRequest request, Page<TPersonYearPointDetailVo> page, TPersonYearPointDetailVo personYearPointDetail){
		ResultData result = new ResultData();
		try{
			User user = this.getLoginUserInfo(request);
			personYearPointDetail.setOrgId(user.getBaseOrgId());
			personYearPointDetailService.findPersonYearPointDetailPageList(page,personYearPointDetail);
			result.setSuccess(true);
			result.setData(page);
			LOG.info("查询积分管理成功");
		}catch (Exception e){
			result.setSuccess(false);
			result.setErrorMsg("查询失败");
			e.printStackTrace();
		}
		return result;
	}

	/**
	 * 导出报表
	 */
	@GetMapping("/exportExcel")
	public void exportExcel(HttpServletRequest request, HttpServletResponse response,TPersonYearPointDetailVo personYearPointDetail) {
		try {
			User user = this.getLoginUserInfo(request);
			//查询要导出的报表数据
			personYearPointDetail.setOrgId(user.getBaseOrgId());
			List<TPersonYearPointDetail> list = personYearPointDetailService.findPersonYearPointDetailList(personYearPointDetail);
			//获取标题
			String[] personYearPointDetailHeads = personYearPointDetailHead.split(",");
			//sheet名称
			String sheetName = "积分报表导出";
			//获取数据
			String[][] Content = ExcelExportUtil.makePersonYearPointDetailHead(list, personYearPointDetailHeads);
			//创建workbook
			XSSFWorkbook workbook = new XSSFWorkbook();
			workbook = ExcelExportUtil.exportExcel(workbook, personYearPointDetailHeads, Content, sheetName);//基本信息
			//响应生成excel
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd-hh-mm-ss");
			LOG.info("开始导出excel报表");
			exportExcel2Browser(response, sheetName + sdf.format(new Date()), workbook);
			LOG.info("导出excel报表成功");
		} catch (Exception e) {
			LOG.error("导出失败");
			e.printStackTrace();
		}
	}

	/**
	 *
	 * 向页面导出excel
	 *
	 * @param response
	 * @param fileName 文件名称
	 * @param workbook 工作簿
	 */
	private void exportExcel2Browser(HttpServletResponse response, String fileName, XSSFWorkbook workbook) {
		OutputStream os = null;
		try {
			// 解决文件乱码
			fileName = URLEncoder.encode(fileName, "UTF8").replaceAll("\\+", "%20");// 其他浏览器
			response.setContentType("application/vnd.ms-excel;charset=UTF-8");
			response.setHeader("Content-Disposition", "attachment;filename=" + fileName + ".xlsx");
			response.addHeader("Pargam", "no-cache");
			response.addHeader("Cache-Control", "no-cache");
			os = response.getOutputStream();
			workbook.write(os);
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (os != null) {
				try {
					os.flush();
					os.close();
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		}
	}

	/**
	 * 普通人员提交申报--保存积分明细,如果已经申报提交，则删除之前的积分明细
	 * @param request
	 * @param personYearPointDetail
	 * @return
	 */
	@RequestMapping("/savePersonYearPointInfo")
	@ResponseBody
	public ResultData savePersonYearPointInfo(HttpServletRequest request, TPersonYearPointDetail personYearPointDetail){
		ResultData result = new ResultData();
		try{
			if(StringUtil.isNullOrEmpty(personYearPointDetail.getSalaryId())){
				result.setErrorMsg("薪档申报ID不能为空");
				result.setSuccess(false);
				return result;
			}
			User user = this.getLoginUserInfo(request);
			TSalaryInfo salaryInfo = salaryService.selectTSalaryInfoById(personYearPointDetail.getSalaryId());
			if(!salaryInfo.getErpNo().equals(user.getFax())){
				result.setSuccess(false);
				result.setErrorMsg("只能提交本人薪档数据，请尝试退出后重新登录！");
				return result;
			}
			//只能申报上年度，如果不是，驳回
			Calendar date = Calendar.getInstance();
			int currentYear = Integer.valueOf(date.get(Calendar.YEAR));
			int appYear = currentYear - 1;
			if(personYearPointDetail.getYear().equals(appYear)){
				this.personYearPointDetailService.saveInfo(personYearPointDetail,user);
				result.setData("保存成功");
				result.setSuccess(true);
			}else{
				result.setData("无法申报该年度，只能申报当前年度的上一年度");
				result.setSuccess(false);
			}
		}catch (Exception e){
			result.setSuccess(false);
			result.setErrorMsg("保存失败");
		}
		return result;
	}

	/**
	 * 管理员审核同意：1、保存积分到积分汇总表；2、申报状态设为同意
	 */
	@RequestMapping("/auditAgreePersonYearPointInfo")
	@ResponseBody
	public ResultData auditPersonYearPointInfo(HttpServletRequest request,String salaryId){
		ResultData result = new ResultData();
		try{
			User user = this.getLoginUserInfo(request);
			personYearPointService.auditAgreeInfo(salaryId,user);
			result.setSuccess(true);
			result.setData("操作成功");
		}catch (Exception e){
			e.printStackTrace();
			result.setSuccess(false);
			result.setErrorMsg("操作失败");
		}
		return result;
	}

	/**
	 * 管理员驳回：1、删除积分明细；2、申报状态设为不同意
	 */
	@RequestMapping("/auditRejectPersonYearPointInfo")
	@ResponseBody
	public ResultData auditRejectPersonYearPointInfo(HttpServletRequest request,String salaryId,String auditOpt){
		ResultData result = new ResultData();
		try{
			User user = this.getLoginUserInfo(request);
			personYearPointDetailService.auditRejectInfo(salaryId,user,auditOpt);
			result.setSuccess(true);
			result.setData("操作成功");
		}catch (Exception e){
			e.printStackTrace();
			result.setSuccess(false);
			result.setErrorMsg("操作失败");
		}
		return result;
	}

	/**
	 * 个人积分页面查询
	 */
	@RequestMapping("/getPersonalYearPointDetail")
	@ResponseBody
	public ResultData getPersonalYearPointDetail(HttpServletRequest request, String year){
		ResultData result = new ResultData();
		try{
			User user = this.getLoginUserInfo(request);
			TPersonYearPointDetailVo tPersonYearPointDetailVo=personYearPointDetailService.getPersonalYearPointDetail(year,user.getBaseOrgId(),user.getFax());
			result.setSuccess(true);
			result.setData(tPersonYearPointDetailVo);
			LOG.info("查询个人积分详情成功");
		}catch (Exception e){
			result.setSuccess(false);
			result.setErrorMsg("查询个人积分详情失败");
			e.printStackTrace();
		}
		return result;
	}

}
